<?php

namespace App\Request\auth\Service\User;

use App\Exception\BusinessException;
use App\Http\Api\CurrentUser;
use App\Repository\User\UserRepository;
use App\Request\auth\Service\IService;
use App\Request\auth\Service\Jwt\JwtService;
use Exception;

/**
 * 用户管理 Service类
 */
class UserService extends IService
{
    public function __construct(
        protected readonly UserRepository $repository,
        protected readonly CurrentUser    $currentUser,
        protected readonly JwtService     $jwtService
    )
    {
    }


    /**
     * PC登录
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function login(array $data): array
    {
        $user = $this->repository->findByFilter([
            'account' => $data['account']
        ]);
        if (!$user) {
            throw new BusinessException("账号不存在");
        }
        if (!password_verify($data['password'], $user->password)) {
            throw new BusinessException( '密码错误');
        }
        if ($user->status != 1) {
            throw  new BusinessException('用户被禁用');
        }
        $token = $this->jwtService->setGuard('user')->getToken($user->id);
        return array_merge($user->toArray(), ['token' => $token]);

    }
}